#include <iostream>
#include <cstdio>
using namespace std;

#include <unistd.h>
#include <pthread.h>


//1.题目描述：线程A打印-我是线程A；线程B打印-我是线程B； 最终实现交替打印，不能出现连续的相同打印。

struct Print 
{
public:
    Print()
    {
        pthread_mutex_init(&_lock,nullptr);
        pthread_cond_init(&_cond,nullptr);
        _flag = 1;
    }

    ~Print()
    {
        pthread_mutex_destroy(&_lock);
        pthread_cond_destroy(&_cond);
    }

public:
    pthread_mutex_t _lock;
    pthread_cond_t _cond;
    bool _flag;
};



void* Print_A(void* args)
{
    Print* p = static_cast<Print*>(args);

    while(1)
    {
        pthread_mutex_lock(&p->_lock);
        while(p->_flag == 0)
            pthread_cond_wait(&p->_cond,&p->_lock);
        
        printf("我是线程A\n");
        sleep(1);
        p->_flag = 0;
        pthread_cond_signal(&p->_cond);
        pthread_mutex_unlock(&p->_lock);
    }

    return nullptr;
}


void* Print_B(void* args)
{
    Print* p = static_cast<Print*>(args);
    
    while(1)
    {
        pthread_mutex_lock(&p->_lock);
        while(p->_flag == 1)
            pthread_cond_wait(&p->_cond,&p->_lock);
        
        printf("我是线程B\n");
        sleep(1);
        p->_flag = 1;
        pthread_cond_signal(&p->_cond);
        pthread_mutex_unlock(&p->_lock);
    }

    return nullptr;
}

int main()
{
    pthread_t A,B;
    Print* p = new Print();
    pthread_create(&A,nullptr,Print_A, p);
    pthread_create(&B,nullptr,Print_B, p);

    pthread_join(A,nullptr);
    pthread_join(B,nullptr);
    
    delete p;

    return 0;
}